//
//  MyProfileViewController.m
//  TipsProject
//
//  Created by Suny on 15/5/2.
//  Copyright (c) 2015年 Suny. All rights reserved.
//

#import "MyProfileViewController.h"
#import "UIBarButtonItem+BaseFramework.h"
#import "RefreshControl.h"
#import "PersonPannel.h"
#import "UserService.h"
#import "TipsService.h"
#import "LoadMoreControl.h"
#import "TipAbstractWaterfallFlowCell.h"
#import "TipAbstractWaterfallFlowLayout.h"
#import "LNWaterfallFlowFooterView.h"
#import "WaterFlowDisplayInfo.h"
#import "TipInfoDetailViewController.h"

#import "FriendService.h"
#import "FriendCollectionCell.h"


@interface MyProfileViewController ()
@property(nonatomic, strong) UserService *service;
@property(nonatomic, strong) RefreshControl *refreshControl;
@property(nonatomic, strong) LoadMoreControl *loadMoreControl;
@property(nonatomic, strong) PersonPannel *personPannel;
// 瀑布流布局
@property (strong, nonatomic) TipAbstractWaterfallFlowLayout *waterfallFlowLayout;
@property(nonatomic, strong)  UICollectionView *collectionView;

#pragma --
#pragma mark - tips
@property (nonatomic, strong)TapItemView *currentTapItemView;
@property (nonatomic, strong)TipsService *tipService;
@property (nonatomic, strong) NSMutableArray * tipAbstractArray;

#pragma --
#pragma mark - attend

@property (nonatomic, strong) NSMutableArray * attentionArray;// 底部视图
@property (nonatomic, strong) FriendService *friendService;

#pragma --
#pragma mark - attended
@property (nonatomic, strong) NSMutableArray * attentionedArray;// 底部视图

@property (nonatomic, strong) LNWaterfallFlowFooterView *footerView;

@property (nonatomic) NSInteger attentionPage;
@property (nonatomic) NSInteger attentionedPage;
@property (nonatomic) NSInteger currentPage;

@end

@implementation MyProfileViewController


- (UserService *)service
{
	if (!_service) 
	{
		_service = [[UserService alloc]initDefaultBaseUrlString];
	}
	
	return _service;
}

- (TipsService *)tipService
{
	if (!_tipService)
	{
		_tipService = [[TipsService alloc] initDefaultBaseUrlString];
		
	}
	return _tipService;
}

- (FriendService *)friendService
{
	if (!_friendService)
 {
		_friendService = [[FriendService alloc] initDefaultBaseUrlString];
	}
	return _friendService;
}


- (RefreshControl *)refreshControl
{
	if (!_refreshControl)
	{
		_refreshControl = [RefreshControl refreshControlWithAttachedView:self.collectionView
																   style:RefreshControlStyleArrow];
		
	}
	return _refreshControl;
	
}

- (LoadMoreControl *)loadMoreControl
{
	if (!_loadMoreControl)
	{
		_loadMoreControl = [[LoadMoreControl alloc] initWithFrame:CGRectMake(0, 0, self.collectionView.width, 44) 
													 attachedView:self.collectionView];
		
		[_loadMoreControl addTarget:self action:@selector(triggerLoadMore)
				   forControlEvents:UIControlEventValueChanged];
		
	}
	
	return _loadMoreControl;
}

- (NSMutableArray *)tipAbstractArray
{
	if (_tipAbstractArray == nil)
	{
		_tipAbstractArray = [NSMutableArray array];
	}
	return _tipAbstractArray;
}

- (NSMutableArray *)attentionArray
{
	if (_attentionArray == nil)
	{
		_attentionArray = [NSMutableArray array];
	}
	return _attentionArray;
}


- (NSMutableArray *)attentionedArray
{
	if (_attentionedArray == nil)
	{
		_attentionedArray = [NSMutableArray array];
	}
	return _attentionedArray;
}
#pragma -
#pragma mark - life circle


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
	self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
	if (self)
	{
		self.waterfallFlowLayout = [[TipAbstractWaterfallFlowLayout alloc] init];
        // 设置布局的属性
        self.waterfallFlowLayout.columnCount = 2;
        self.waterfallFlowLayout.sectionInset = UIEdgeInsetsMake(0, 10,10, 10);
        self.waterfallFlowLayout.sectionHeaderHeight = 250;

	}
	
	return self;
}

- (void)viewDidLoad 
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
	
	
	self.view.height -= self.customTabViewController.tabBarHeight;
	
	if ([[LoginUserInfo sharedInstance].userId isEqualToString:self.userInfo.userId])
	{
//		UIBarButtonItem *left = [UIBarButtonItem leftBarButtonItemWithImageName:@"app_setting"
//																		 target:self
//																	   selector:@selector(handleTapLeftBarButtonItem)];
//		
//		UIBarButtonItem *right = [UIBarButtonItem rightBarButtonItemWithImageName:@"nav_menu_gray_button"
//																		   target:self
//																		 selector:@selector(handleTapRightBarButtonItem)];
//		self.navigationItem.leftBarButtonItem = left;
//		self.navigationItem.rightBarButtonItem = right;
		[self setNavigationTitle:@"个人中心"];

	}
	else
	{
		self.navigationItem.leftBarButtonItem = self.defaultBackButtonItem;
		[self setNavigationTitle:self.userInfo.nickName];
	}
	

	


	self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 
																			 self.navigationBarHeight,
																			 self.view.width, 
																			 self.view.height - (self.hasNavigationBar?self.navigationBarHeight:0))
											 collectionViewLayout:self.waterfallFlowLayout];
	self.collectionView.delegate = self;
	self.collectionView.dataSource = self;
	
	self.collectionView.alwaysBounceVertical = YES;
	UIView *backgroundView = [[UIView alloc] initWithFrame:self.collectionView.bounds];
	backgroundView.backgroundColor = [UIColor colorWithHexString:@"dbdbdb"];
	self.view.backgroundColor =  [UIColor colorWithHexString:@"dbdbdb"];
	self.collectionView.backgroundView = backgroundView;
	
	[self.view addSubview:self.collectionView];
	
	[self.refreshControl addTarget:self 
							action:@selector(requestDataFromNet) 
				  forControlEvents:UIControlEventValueChanged];

	
	
	[self loadTipView];
}



- (void)didReceiveMemoryWarning 
{
	[super didReceiveMemoryWarning];
	// Dispose of any resources that can be recreated.
}



#pragma --
#pragma mark - UICollectionView 相关

// The view that is returned must be retrieved from a call to -dequeueReusableSupplementaryViewOfKind:withReuseIdentifier:forIndexPath:  
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView
		   viewForSupplementaryElementOfKind:(NSString *)kind 
								 atIndexPath:(NSIndexPath *)indexPath
{  
	
	NSString *reuseIdentifier;  
	if ([kind isEqualToString: UICollectionElementKindSectionFooter ])
	{  
		reuseIdentifier = @"kfooterIdentifier";  
	}
	else
	{  
		reuseIdentifier = @"kheaderIdentifier";  
	}  
	
	UICollectionReusableView *view =  [collectionView dequeueReusableSupplementaryViewOfKind:kind   
																		 withReuseIdentifier:reuseIdentifier   
																				forIndexPath:indexPath];  
	
	if ([kind isEqualToString:UICollectionElementKindSectionHeader])
	{  
		self.personPannel =(PersonPannel *) view;
		self.personPannel.userInfo = self.userInfo;
		self.personPannel.pannelDelegate = self; 
		
	}  
	else if ([kind isEqualToString:UICollectionElementKindSectionFooter])
	{  
		self.footerView = (LNWaterfallFlowFooterView *)view;
		[self.footerView addSubview:_loadMoreControl];
	}  
	return view;  
}  




- (void)loadTipView
{
	
	
	[self.collectionView registerClass:[TipAbstractWaterfallFlowCell class] forCellWithReuseIdentifier:@"CellCache"];
    [self.collectionView registerClass:[FriendCollectionCell class] forCellWithReuseIdentifier:@"friendCellCache"];
	[self.collectionView registerClass:[LNWaterfallFlowFooterView class]
			forSupplementaryViewOfKind:UICollectionElementKindSectionFooter
				   withReuseIdentifier:@"kfooterIdentifier"];

	[self.collectionView registerClass:[PersonPannel class]
			forSupplementaryViewOfKind:UICollectionElementKindSectionHeader
				   withReuseIdentifier:@"kheaderIdentifier"];
	
	self.collectionView.backgroundColor = [UIColor whiteColor];
	
	[WaterFlowDisplayInfo setWidth: (self.collectionView.bounds.size.width - self.waterfallFlowLayout.sectionInset.left - self.waterfallFlowLayout.sectionInset.right)];
	
	
	WEAKSELF;
	[self.tipService getCollectTips:self.currentPage
						finishBlock:^(BaseResponse *response) {
							STRONGSELF
							[strongSelf handleGetTipResponse:response];
						} ];
}

//section  
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView  
{  
	return 1;  
}  



#pragma mark - 数据源方法
- (NSInteger)collectionView:(UICollectionView *)collectionView 
	 numberOfItemsInSection:(NSInteger)section 
{
	if (self.personPannel.state == PersonPannelTapStateTips)
	{
		return self.tipAbstractArray.count;
	}
	else if (self.personPannel.state == PersonPannelTapStateAttention)
	{
		return self.attentionArray.count;
	}
	else if (self.personPannel.state == PersonPannelTapStateAttentioned)
	{
		return self.attentionedArray.count;	
	}

	return 0;

	
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView 
				  cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.personPannel.state == PersonPannelTapStateTips)
    {

        // 创建可重用的cell
        TipAbstractWaterfallFlowCell *cell = [collectionView
                dequeueReusableCellWithReuseIdentifier:@"CellCache"
        forIndexPath:indexPath];
        // background
		cell.backgroundColor = [UIColor whiteColor];
		
		// shadow
		cell.layer.shadowColor = [UIColor colorWithWhite:0.12 alpha:1].CGColor;
		cell.layer.shadowOffset = CGSizeMake(0, 0.5);
		cell.layer.shadowRadius = 1;
		cell.layer.shadowOpacity = 1;
		cell.layer.cornerRadius = 4;
		cell.clipsToBounds = YES;

        cell.good = self.tipAbstractArray[indexPath.item];
        return cell;
    }
    else
    {
        // 创建可重用的cell
        FriendCollectionCell *cell = [collectionView
                dequeueReusableCellWithReuseIdentifier:@"friendCellCache"
                                          forIndexPath:indexPath];
		cell.backgroundColor = [UIColor whiteColor];
		
		// shadow
		cell.layer.shadowColor = [UIColor colorWithWhite:0.12 alpha:1].CGColor;
		cell.layer.shadowOffset = CGSizeMake(0, 0.5);
		cell.layer.shadowRadius = 1;
		cell.layer.shadowOpacity = 1;
		cell.layer.cornerRadius = 4;
		cell.clipsToBounds = YES;
		if (self.personPannel.state == PersonPannelTapStateAttention)
		{
			cell.displayInfo = self.attentionArray[indexPath.item];
		}
		else
		{
			cell.displayInfo = self.attentionedArray[indexPath.item];
		}

		
        return cell;

    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
	DLogObject(indexPath);
	if (self.personPannel.state == PersonPannelTapStateTips)
	{
		
		TipInfoDetailViewController *detailViewController = [[TipInfoDetailViewController alloc] init];
		detailViewController.previewMode = NO;
		
		TipAbstractWaterfallFlowCell *cell = (TipAbstractWaterfallFlowCell *)[collectionView cellForItemAtIndexPath:indexPath];
		
		TipInfo *tipInfo = [[TipInfo alloc] init];
		tipInfo.tipId = cell.good.abstract.tipId;
		
		detailViewController.tipInfo = tipInfo;
		
		NavigationController *nav = [AppDelegate rootNavigationController];
		
		[nav pushViewController:detailViewController
					   animated:YES];

	}
	else 
	{
		
		FriendCollectionCell *cell = (FriendCollectionCell *)[collectionView cellForItemAtIndexPath:indexPath];

		
		MyProfileViewController *profileViewController = [[MyProfileViewController alloc] init];
		profileViewController.userInfo = cell.displayInfo.userInfo;
		profileViewController.navigationItem.rightBarButtonItem = profileViewController.defaultBackButtonItem;

		profileViewController.hasNavigationBar = YES;
		NavigationController *nav = [AppDelegate rootNavigationController];
		
		[nav pushViewController:profileViewController
					   animated:YES];
		
	}
}


/**
 *  加载数据
 */
- (void)loadData
{
	self.waterfallFlowLayout.goodsList = self.tipAbstractArray;
	//	// 刷新数据
	[self.collectionView reloadData];
}


#pragma --
#pragma mark -  button 事件 


- (void)handleTapLeftBarButtonItem
{
	
}

- (void)handleTapRightBarButtonItem
{
	
}

#pragma --
#pragma mark -  refresh and loadMore

- (void)triggerLoadMore
{
	if (self.personPannel.state == PersonPannelTapStateTips)
	{
		self.currentPage ++;	
		
		[self requestAbstractListData];
	}
	else if (self.personPannel.state == PersonPannelTapStateAttention)
	{
		self.attentionPage ++;
		[self requestAttentionData];
	}
	else
	{
		self.attentionedPage ++;
		[self requestAttentionedData];
	}
	
}



- (void)requestDataFromNet
{
	WEAKSELF
	[self.service queryUserInfo:self.userInfo
				withFinishBlock:^(BaseResponse *response) {
					STRONGSELF
					
					if (response.success)
					{
						strongSelf.userInfo = response.object;
						strongSelf.personPannel.userInfo = response.object;
						if (strongSelf.personPannel.state == PersonPannelTapStateTips)
						{
							self.currentPage = 0;
							[strongSelf requestAbstractListData];
						}
						else if (strongSelf.personPannel.state == PersonPannelTapStateAttention)
						{
							self.attentionPage = 0;
							[strongSelf requestAttentionData];
						}
						else
						{
							
							self.attentionedPage = 0;
							[strongSelf requestAttentionedData];
						}
					}
					else
					{
						if (response.httpResponseCode == 200) 
						{
							[strongSelf showErrorMessage:NetWork_NotReachable];
						}
						else 
						{
							[strongSelf showErrorMessage:Data_Error];
							
						}
					}
					
					[strongSelf.refreshControl  endRefreshing];
					[strongSelf.refreshControl refreshLastUpdatedTime:[NSDate date]];
				}];
}



#pragma --
#pragma mark -  网络数据处理 



- (void)requestAbstractListData
{
	[self requestTipsListWithTapTipSegmentIndex:self.personPannel.segmentIndex];
}



- (void)handleGetTipResponse:(BaseResponse *)response
{
	[self.coverView stopAnimating];
	self.coverView.top = - 100;
	[self.refreshControl endRefreshing];
	[self.loadMoreControl endLoading];
	
	
	if (response.httpResponseCode == 200) //网络是否联通
	{
		if (response.success)//服务器是否成功处理
		{
			if ([response.object isKindOfClass:[NSArray class]]) //数据格式是否正确
			{
				if (self.currentPage == 0)
				{
					[self.tipAbstractArray removeAllObjects];
				}
				
				[self.tipAbstractArray addObjectsFromArray:response.object];
				
				if ([response.object count] < kDefaultPageSize)
				{
					[self.loadMoreControl removeFromSuperview];
					self.loadMoreControl = nil;
				}
				else
				{
					[self.footerView addSubview:self.loadMoreControl];
				}
				[self loadData];
			}
			else
			{
				[self showErrorMessage:Data_Error];
				self.currentPage --;
			}
		}
		else
		{
			[self showErrorMessage:response.desc];
			self.currentPage --;

		}
		
	}
	else
	{
		[self showErrorMessage:NetWork_NotReachable];
		
		if ([self.tipAbstractArray count] == 0)
		{
			[self.coverView stopAnimationWithRetryAction:@selector(requestAbstractListData)
										   withActObject:self];
		}
		self.currentPage --;
	}
	
}

- (void)requestAttentionData
{
    WEAKSELF
	[self.friendService getFollowFriendByUserId:[self.userInfo userId]
										pageIndex:self.attentionPage
									  finishBlock:^(BaseResponse *response) {
        STRONGSELF
        [strongSelf handleGetAttentionResponse:response];
									  }];
}


- (void)handleGetAttentionResponse:(BaseResponse *)response
{
	[self.coverView stopAnimating];
	self.coverView.top = - 100;
	[self.refreshControl endRefreshing];
	[self.loadMoreControl endLoading];
	
	if (response.success)
    {
        NSMutableArray *displayInfoArray = [NSMutableArray array];
        NSArray *userInfoArray = response.object;

        for (UserInfo * userInfo in userInfoArray)
        {
            FriendFloawDisplayInfo *displayInfo = [[FriendFloawDisplayInfo alloc] init];
            displayInfo.userInfo = userInfo;
            displayInfo.w = self.collectionView.width/3.0;
            displayInfo.h = displayInfo.w +  40;

            [displayInfoArray addObject:displayInfo];
        }

		if (self.attentionPage == 0)
		{
			[self.attentionArray removeAllObjects];
		}
		
		
        [self.attentionArray addObjectsFromArray:displayInfoArray];
        self.waterfallFlowLayout.goodsList = self.attentionArray;

		
		if ([response.object count] < kDefaultPageSize)
		{
			[self.loadMoreControl removeFromSuperview];
			self.loadMoreControl = nil;
		}
		else
		{
			[self.footerView addSubview:self.loadMoreControl];
		}
		
        [self.collectionView reloadData];
    }
    else
    {
        if (response.httpResponseCode == 200)
        {
            [self showErrorMessage:Data_Error];
		}
        else
        {
            [self showErrorMessage:NetWork_NotReachable];
        }
		
		self.attentionPage --;
    }
}


- (void)requestAttentionedData
{

	WEAKSELF
    [self.friendService getFollowedFriendByUserId:[self.userInfo userId]
										pageIndex:self.attentionedPage
									  finishBlock:^(BaseResponse *response) {
										  STRONGSELF
										  [strongSelf handleGetAttentionedResponse:response];
									  }];
}


- (void)handleGetAttentionedResponse:(BaseResponse *)response
{
	if (response.success)
	{
		NSMutableArray *displayInfoArray = [NSMutableArray array];
		NSArray *userInfoArray = response.object;
		
		for (UserInfo * userInfo in userInfoArray)
		{
			FriendFloawDisplayInfo *displayInfo = [[FriendFloawDisplayInfo alloc] init];
			displayInfo.userInfo = userInfo;
			displayInfo.w = self.collectionView.width/3.0;
			displayInfo.h = displayInfo.w +  40;
			
			[displayInfoArray addObject:displayInfo];
		}
		if (self.attentionedPage == 0)
		{
			[self.attentionedArray removeAllObjects];
		}
		[self.attentionedArray addObjectsFromArray:displayInfoArray];
		self.waterfallFlowLayout.goodsList = self.attentionedArray;
		
		
		
		if ([response.object count] < kDefaultPageSize)
		{
			[self.loadMoreControl removeFromSuperview];
			self.loadMoreControl = nil;
		}
		else
		{
			[self.footerView addSubview:self.loadMoreControl];
		}
		
		[self.collectionView reloadData];
	}
	else
	{
		self.attentionedPage --;
		if (response.httpResponseCode == 200)
		{
			[self showErrorMessage:Data_Error];
		}
		else
		{
			[self showErrorMessage:NetWork_NotReachable];
		}
	}
}
#pragma -
#pragma -- delegate
- (void)personPannel:(PersonPannel *)pannel tapItem:(TapItemView *)itemView
{
	if (itemView.tag == self.currentTapItemView.tag)
	{
		return;
	}
	
	if (itemView.tag == 1000)
    {
        self.waterfallFlowLayout.sectionHeaderHeight = 250;
		self.waterfallFlowLayout.columnCount = 2;
		self.waterfallFlowLayout.goodsList = self.tipAbstractArray;
		[self.collectionView reloadData];
//		if (self.tipAbstractArray.count == 0)
//		{
//			[self personPannel:self.personPannel
//			tapTipSegmentIndex:self.personPannel.segmentIndex];
//		}

    }
    else
    {
		if (itemView.tag == 2000)
		{
			self.waterfallFlowLayout.goodsList = self.attentionArray;
			[self requestAttentionData];
		}
		else
		{
			self.waterfallFlowLayout.goodsList = self.attentionedArray;

			[self requestAttentionedData];
		}
		
		self.waterfallFlowLayout.sectionHeaderHeight = 200;
		self.waterfallFlowLayout.columnCount = 3;
		
		[self.collectionView reloadData];

    }
	
	self.currentTapItemView = itemView;
    [self.collectionView reloadData];
}

- (void)personPannel:(PersonPannel *)pannel tapTipSegmentIndex:(NSInteger)index
{
	self.currentPage = 0;
	[self requestTipsListWithTapTipSegmentIndex:index];
}

- (void)requestTipsListWithTapTipSegmentIndex:(NSInteger)index
{
	WEAKSELF
	if (index == 0)
	{
		[self.tipService getCollectTips:self.currentPage
								 userId:self.userInfo.userId
							finishBlock:^(BaseResponse *response) {
								STRONGSELF
								[strongSelf handleGetTipResponse:response];
							} ];
	}
	else if (index == 1)
	{
		[self.tipService getCreateTips:self.currentPage
								userId:self.userInfo.userId
						   finishBlock:^(BaseResponse *response) {
							   STRONGSELF
							   [strongSelf handleGetTipResponse:response];
						   } ];
	}
	else
	{
		[self.tipService getInterestedTips:self.currentPage
									userId:self.userInfo.userId
							   finishBlock:^(BaseResponse *response) {
								   STRONGSELF
								   [strongSelf handleGetTipResponse:response];
							   } ];
	}
}




@end
